<?php

namespace addons\crontab\model;

use think\Model;
use think\Db;
use app\admin\model\inventory\Temporary;
use think\Log;
use fast\Auth;
use addons\crontab\model\Rdrecord01extra;

//采购入库单
class RdRecord01 extends Model
{
    protected $connection = "database.inc";
    protected $table = "RdRecord01";
    
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'datetime';
    // 定义时间戳字段名
    protected $createTime = 'dnmaketime';
    protected $updateTime = 'dnmodifytime';
    // 定义字段类型
    protected $type = [
    ];
    // 追加属性
    protected $append = [
    ];
    
    /*
     * 新增数据（表头）,返回表头对象
     *   */
    public function insertMain($data,$u8type){
        if(!$data){
            exception('RdRecord01表头为空');
        }
        //采购入库，源单不为空
        if($u8type==1&&!isset($data['source_code'])){
            exception('RdRecord01源单编码为空');
        }
        
        $model =  self::where('cCode',$data['code'])->find();
        $auth = Auth::instance();
        
        if(!$model){
            
            //得到原采购订单
            if(isset($data['source_code'])&&!empty($data['source_code'])){
                $pomain = Db::connect('database.sec')->table('PO_Pomain')->where('cPOID',$data['source_code'])->find();
                if(!$pomain){
                    exception('找不到U8采购订单');
                }
                $pomain_extra = Db::connect('database.sec')->table('PO_Pomain_extradefine')
                ->where('POID',$pomain['POID'])
                ->field('chdefine3,chdefine4,chdefine5,chdefine6,chdefine7')
                ->find();
            }
            
            //针对收货的单据，要先把中间库的表体记录删了，保留表头 20231108,针对重新复核的，
            $rd01 = RdRecord01::get(['cCode'=>$data['code']]);
            if($rd01){
                Rdrecords01::destroy(['ID'=>$rd01->ID]);
            }
            
            //-- 更新采购入库单状态为红字
            //UPDATE RdRecord01 SET cVouchType = '红字' WHERE cVouchID = 'your_vouch_id';
            //当 bRdFlag 的取值为 1 时，表示该采购入库单是收货操作。即从供应商处收到物品，并将其入库到自己的库存中。
            //当 bRdFlag 的取值为 0 时，表示该采购入库单是发货操作
            //表头
            $model = self::allowField(true)->create([
                'ID'=>Crontab::getAutoIDByTname('RdRecord01'),//收发记录主表标识   表头id 自增
                'bRdFlag'=> 1,//收发标志
                'cVouchType' => '01',//'01'单据类型编码
                'cBusType' => '普通采购',
                'cSource' => $u8type==1?'采购订单':'库存',//采购退回
                'cCode'=>$data['code'],//插入中间库的，就直接用pda的单号来用
                'cRdCode'=>'12',
                'cWhCode' => $data['wh_code'],
                'dDate'=>$data['order_date'],
                'cDepCode'=> isset($pomain['cDepCode'])?$pomain['cDepCode']:'',
                'cPersonCode'=> isset($pomain['cPersonCode'])?$pomain['cPersonCode']:'',//业务员编码
                'cPTCode'=>'01',
                'cVenCode'=>isset($pomain['cVenCode'])?$pomain['cVenCode']:'',
                'cOrderCode' => isset($data['source_code'])?$data['source_code']:'',
                'cMaker' =>$auth->u8_user_name,//制单人 //u8用户名
                //'cHandler' =>$auth->u8_handler_name,//审核人 //u8用户名
                //dVeriDate	审核日期
                //dnverifytime	审核时间
                'cMemo' => isset($data['remark'])?$data['remark']:'',//表头备注
                'VT_ID' => 55,
                'ipurorderid' => isset($pomain['POID'])?$pomain['POID']:'',//采购订单主表标识
                'dnmaketime' => date('Y-m-d',time()), //制单日期
                //'cHandler' => $data['userid'], //审核人
                //'dVeriDate' => date('Y-m-d',time()) //审核日期
            ]);
            
            //插入扩展表，协议相关字段
            if(isset($pomain_extra['chdefine3'])){
                $pomain_extra['ID'] = $model->ID;
                unset($pomain_extra['ROW_NUMBER']);
                Rdrecord01extra::create($pomain_extra);
            }
        }
        return $model;
    }
    
    //回写u8存储过程并更新采购订单数量，状态
    /*
     * 传入参数，表头流水号ID，账套编号001、999
     * 返回状态0成功 、1失败，和结果
     *   */
    public function synDataToU8($main_id,$dbname = '888'){
        if(!$main_id){
            exception('表头ID不能为空');
        }
        
        $sql = "SET NOCOUNT ON;declare @p6 varchar(1000)
        declare @p7 int
        exec sily_generator_RdRecord01_sync '{$main_id}','{$dbname}',@p6 output,@p7 output
        select @p6 as result ,@p7 as status";
        
        $arr = Db::connect('database.inc')->query($sql);
        
        if(!isset($arr[0]['status'])){
            exception('回写u8失败');
        }
        
        if(!$arr[0]['status']){
            exception('回写u8失败:'.$arr[0]['result']);
        }else{
            //回写成功，返回u8单号
            $temporaryModel = new Temporary();
            $temporary = $temporaryModel->save([
                'u8_code' => $arr[0]['result']
            ],[
                'mid_rdrecord_id'=>$main_id
            ]);
        }
    }
    
    /*
     * 更新采购订单已收数量（不然u8无法删除采购入库单），操作u8正式账套
     *   */
    public function updateU8PoDetailRecQty($poDetail_ID,$iQuantity){
        if(!$poDetail_ID||!$iQuantity){
            return ;
        }
        //trace([$poDetail_ID,$iQuantity],'error');
        //Log::write([$poDetail_ID,$iQuantity],'info');
        //坑，iReceivedQTY为空时，无法自增数量，得先赋值0
        /*Db::connect('database.sec')->table('PO_Podetails')
         ->where( ['ID'=>$poDetail_ID])->setInc('iReceivedQTY',$iQuantity);*/
        
        $row = \app\admin\model\information\U8Podetails::where( ['ID'=>$poDetail_ID])->find();
        if(!$row->iReceivedQTY){
            $row->iReceivedQTY = 0;
            $row->save();
        }
        \app\admin\model\information\U8Podetails::where( ['ID'=>$poDetail_ID])->setInc('iReceivedQTY',$iQuantity);
    }
    
    /*
     * //更新采购订单状态，操作u8正式账套
     *   */
    public function updateU8Po($source_code,$dbname = '888'){
        if(!$source_code){
            exception('采购订单编码不能为空');
        }
        
        //取到该采购订单，未关闭的所有表体记录
        //$source_code = 'po2023040001';
        
        $poDetails = Db::connect('database.inc')->query("SET NOCOUNT ON;exec sily_fsl '{$source_code}','{$dbname}'");
        
        if(!$poDetails){
            exception('找不到采购单表体明细，无法更新采购单状态');
        }
        
        $i = 0;
        foreach ($poDetails as $poDetail){
            if($poDetail['warehousing_quantity']>=$poDetail['iQuantity']){
                //入库数量大于计划数关闭表体
                //不关闭源单，因为得需要3个条件，入库完成、开票完成、付款核销完成
                Db::connect('database.sec')->table('PO_Podetails')
                ->where('ID',$poDetail['ID'])
                ->update([
                    'cbCloseTime' => date('Y-m-d H:i:s',time()),
                    'cbCloseDate' => date('Y-m-d',time()),
                    'cbCloser' => 'demo' //默认
                ]);
                $i++;
            }
        }
        
        //全部关闭，则关闭表头
        //先不更新采购单状态，u8那边新增无论有无审核，都更新库存
        if($i == count($poDetails)){
            Db::connect('database.sec')->table('PO_Pomain')
            ->where('cPOID',$source_code)
            ->update([
                'cState' => 2,
                'dCloseTime' => date('Y-m-d H:i:s',time()),
                'dCloseDate' => date('Y-m-d',time()),
                'cCloser' => 'demo' //默认
            ]);
        }
    }
}
